import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

import java.time.Duration;

/**
 * @program: junit5_learning
 * @description: 断言
 * @author: CaoYong
 * @create: 2021-03-11 17:43
 **/
public class Assert {

    @Test
    void standardAssertions() {
        Assertions.assertEquals(2,2);
        Assertions.assertEquals(4,4, "error message");
        Assertions.assertTrue(2 ==2, () -> "error");
    }

    @Test
    void groupAssertions() {
        Assertions.assertAll("person",
                () -> Assertions.assertEquals("John", "John"),
                () -> Assertions.assertEquals("Doe", "Doe")
        );
    }

    @Test
    void dependentAssertions() {
        Assertions.assertAll("properties",
                () -> {
                    String firstName = "Jhon";
                    Assertions.assertNotNull(firstName);
                    Assertions.assertAll("firstName",
                            () -> Assertions.assertTrue(firstName.startsWith("J")),
                            () -> Assertions.assertTrue(firstName.endsWith("n")));
                },
                () -> {
                    String lastName = "Doe";
                    Assertions.assertNotNull(lastName);
                    Assertions.assertAll("last name",
                            () -> Assertions.assertTrue(lastName.startsWith("D")),
                            () -> Assertions.assertTrue(lastName.endsWith("e")));
                }
        );
    }

    @Test
    void exceptionTesting() {
        Throwable exception = Assertions.assertThrows(IllegalArgumentException.class, () -> {
            throw new IllegalArgumentException("a message");
        });
        Assertions.assertEquals("a message", exception.getMessage());
    }

    @Test
    void timeoutExceeded() {
        Assertions.assertTimeout(Duration.ofMillis(10), () -> {
            Thread.sleep(1000);
        });
    }

    @Test
    void timeoutExceededWithPreemptiveTermination() {
        Assertions.assertTimeoutPreemptively(Duration.ofMillis(10), () -> {
            Thread.sleep(1000);
        });
    }

}
